from object import Object
from service import Service
from optionServer import optionServer

import glob
import sys
import os.path
import util
import yaml
import stackless

class FileServer(Service):
    def __init__(self):
        Service.__init__(self)
        
        self.dirs = []
        self.files = {}
        
        map(self.addFile,[file.rstrip('/') for file in sys.argv[1:]])
        
        self.loadFunctions = util.getFunctions(self, "load_")
        for ext, files in self.files.iteritems():
            if ext in self.loadFunctions:
                map(self.loadFunctions[ext],files)
                
        self.filePaths = self.buildFilePaths()
        
    def buildFilePaths(self, path = "."):
        filePaths = {}
        
        for name in glob.glob(path + "/*"):
            if os.path.isfile(name):
                filePaths[name.split('/')[-1]] = name
            elif os.path.isdir(name) and name.split("/")[1] in self.dirs:
                filePaths.update(self.buildFilePaths(name))
            
        return filePaths
                
    def load_cfg(self, file):
        optionServer.update(yaml.evalLoad(open(file)))
        
    def load_sim(self, file):
        def doLoadSim():
            for name, vals in yaml.evalLoad(open(file)).iteritems():
                while True:
                    try:
                        from networkServer import networkServer
                        break
                    except:
                        self.schedule()
                recreate = vals.pop('recreate',False)
                if recreate:
                    Object(name,**vals)
                else:
                    if Object.hasObject(name):
                        Object.getObject(name).loadArgs(vals)
                    else:
                        Object(name,**vals)
        stackless.tasklet(doLoadSim)()
                
    def getExtension(self, filename):
        pos = filename.find('.')
        if pos == -1:
            return ''
        else:
            return filename[pos+1:]
        
    def addFile(self, filename, internal = False):
        if not internal:
            self.dirs.append(filename)
        
        if os.path.isfile(filename):
            ext = self.getExtension(filename)
            self.files.setdefault(ext,[]).append(filename)
        elif os.path.isdir(filename):
            for subFile in glob.glob(filename + "/*"):
                self.addFile(subFile,True)

fileServer = FileServer()
fileServer()
